package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Menu2;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu2> getMenus(Integer id) {
        //获取一级菜单
        List<Menu2> menus = menuMapper.getMenusByParentId(id);
        getChildrenMenu(menus);
        return menus;
    }

    @Override
    public List<Menu2> getMenuList(List<Integer> roleIds) {
        Map map = new HashMap();
        map.put("roles", roleIds);
        map.put("id", 0);
        //先查询出角色的一级菜单
        List<Menu2> roleMenus = roleMapper.getRoleMenus(map);
        //递归查询一级以及下面各级菜单的子菜单
        getChildrenMenu(roleMenus, map);
        return roleMenus;
    }

    @Override
    public void add(Menu menu) {

        menu.setPath(UUID.randomUUID().toString());
        menuMapper.add(menu);
    }

    @Override
    public Menu findById(Integer id) {
        return menuMapper.findById(id);
    }

    @Override
    public void menuEdit(Menu menu) {
        roleMapper.menuEdit(menu);
    }

    @Override
    public void menuDelete(Integer id) throws Exception {
        //判断菜单与角色是否有关联
        Integer flag = menuMapper.menuDeletRole(id);
        if (flag > 0) {
            throw new Exception("要删除的数据被使用,无法删除");
        }
        menuMapper.menuDelete(id);
    }


    private void getChildrenMenu(List<Menu2> menus, Map map) {
        for (Menu2 menu : menus) {
            map.put("id", menu.getId());
            List<Menu2> cmenus = roleMapper.getRoleMenus(map);
            menu.setChildren(cmenus);
            getChildrenMenu(cmenus, map);
        }
    }

    private void getChildrenMenu(List<Menu2> menus) {
        if (CollectionUtil.isNotEmpty(menus)) {
            for (Menu2 menu : menus) {
                List<Menu2> cmenus = menuMapper.getMenusByParentId(menu.getId());
                menu.setChildren(cmenus);
                getChildrenMenu(cmenus);
            }
        }
    }
}